﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;

namespace Codemonk.Updater.Server
{
    internal static class WriteInventory
    {
        internal static void Write(string filepath, Inventory inventory)
        {
            XmlDocument document = new XmlDocument();
            document.AppendChild(document.CreateXmlDeclaration("1.0", "utf-8", null));
            var root = document.CreateElement("codemonk.updater.inventory");
            var compulsive = document.CreateElement("compulsive");
            compulsive.InnerText = inventory.IsCompulsive.ToString().ToLower();
            root.AppendChild(compulsive);

            var updatelist = document.CreateElement("updatelist");
            updatelist.InnerText = inventory.UpdateList;
            root.AppendChild(updatelist);

            var entrypoint = document.CreateElement("entrypoint");
            entrypoint.InnerText = inventory.EntryPoint;
            root.AppendChild(entrypoint);

            var items = document.CreateElement("items");

            var collection = inventory.Items;
            foreach (var file in collection)
            {
                var item = document.CreateElement("item");

                var name = document.CreateElement("name");
                name.InnerText = file.Name;
                item.AppendChild(name);

                var hash = document.CreateElement("hash");
                hash.InnerText = file.Hash;
                item.AppendChild(hash);

                var size = document.CreateElement("size");
                size.InnerText = file.Size + "";
                item.AppendChild(size);

                items.AppendChild(item);
            }

            root.AppendChild(items);

            document.AppendChild(root);
            document.Save(filepath);
        }
    }
}
